<template>
    <n-space v-bind="mergedProps" v-if="visible()">
        <slot>
            <GetanButton v-for="v in actions" :options="v" />
        </slot>
    </n-space>
</template>

<script setup lang="ts">
import { GetanButtonGroupProps } from "./types"
import { isEmpty, isUndefined } from "@/utils"
import { GetanButton } from "@/components/Button"
import { hasPermission, isShow } from "@/components/Permission"

const props = defineProps<{
    options?: GetanButtonGroupProps
}>()

const naiveProps = computed(() => {
    const p: Recordable = {}
    if (props.options) {
        const { vertical, size } = props.options
        if (!isUndefined(vertical)) {
            p.vertical = vertical
        }
        if (size) {
            p.size = size
        }
    }
    return p
})

const attrs = useAttrs()

const mergedProps = computed(() => {
    return {
        ...attrs,
        ...unref(naiveProps)
    }
})

const actions = computed(() => {
    const { size, items = [] } = props.options ?? {}
    return items
        .filter(v => isShow(v) && hasPermission(v))
        .map(v => {
            const p = { ...v }
            const { size: currentSize } = v
            if (isUndefined(currentSize)) {
                p.size = size
            }
            p.permissions = undefined
            p.show = undefined
            return p
        })
})

const visible = () => {
    if (props.options) {
        return hasPermission(props.options) && !isEmpty(actions.value)
    }
    return true
}
</script>
